<script setup lang="ts">
import { REPORT_ID, REPORT_FORM_ID } from '@/enum'

import SummaryCompanyElectricityReport1 from '@/components/Reports/summary-company-electricity/index1.vue'
import SummaryCompanyElectricityReport2 from '@/components/Reports/summary-company-electricity/index2.vue'
import SummaryCompanyElectricityReport3 from '@/components/Reports/summary-company-electricity/index3.vue'
import SummaryCompanyWeightReport from '@/components/Reports/summary-company-weight/index.vue'
import SummaryCompanyElectricityCategoryReport from '@/components/Reports/summary-company-electricity-category/index.vue'
import SummaryCompanyPrimaryElectricityDeviceReport1 from '@/components/Reports/summary-company-primary-electricity-device/index1.vue'
import SummaryCompanyPrimaryElectricityDeviceReport2 from '@/components/Reports/summary-company-primary-electricity-device/index2.vue'
import SummaryCompanyPrimaryElectricityDeviceReport3 from '@/components/Reports/summary-company-primary-electricity-device/index3.vue'
import SummaryCompanyPrimaryElectricityDeviceReport4 from '@/components/Reports/summary-company-primary-electricity-device/index4.vue'
import SummaryCompanyPrimaryElectricityDeviceReport5 from '@/components/Reports/summary-company-primary-electricity-device/index5.vue'
import SummaryCompanyPrimaryElectricityDeviceReport6 from '@/components/Reports/summary-company-primary-electricity-device/index6.vue'
import type { TabPaneName } from 'element-plus'
import { saveReportDataOfSummaryCompanyElectricityCost } from '@/api/modules/dataReport'

type ReportRef =
  | InstanceType<typeof SummaryCompanyElectricityReport1>
  | InstanceType<typeof SummaryCompanyElectricityReport2>
  | InstanceType<typeof SummaryCompanyElectricityReport3>
  | InstanceType<typeof SummaryCompanyWeightReport>
  | InstanceType<typeof SummaryCompanyElectricityCategoryReport>
  | InstanceType<typeof SummaryCompanyPrimaryElectricityDeviceReport1>
  | InstanceType<typeof SummaryCompanyPrimaryElectricityDeviceReport2>
  | InstanceType<typeof SummaryCompanyPrimaryElectricityDeviceReport3>
  | InstanceType<typeof SummaryCompanyPrimaryElectricityDeviceReport4>
  | InstanceType<typeof SummaryCompanyPrimaryElectricityDeviceReport5>
  | InstanceType<typeof SummaryCompanyPrimaryElectricityDeviceReport6>

const props = defineProps<{
  month: string
  title: string
  reportId: REPORT_ID
  forceShowTab?: boolean
  readonly?: boolean
  whenTabBeforeLeave: (saveFn: () => Promise<boolean>) => Promise<boolean>
}>()
const emit = defineEmits<{
  (e: 'tabChange', value: TabPaneName): void
}>()
const reportRef = ref<ReportRef>()
const isSummaryCompanyElectricity = computed(() => {
  return props.reportId === REPORT_ID.ELECTRICITY_BILL_SUMMARY
})
const isSummaryCompanyWeight = computed(() => {
  return props.reportId === REPORT_ID.WATER_BALANCE_SUMMARY
})
const isSummaryCompanyElectricityCategory = computed(() => {
  return props.reportId === REPORT_ID.CLASSIFIED_ELECTRICITY_USAGE_SUMMARY
})
const isSummaryCompanyPrimaryElectricityDevice = computed(() => {
  return props.reportId === REPORT_ID.MAIN_ENERGY_CONSUMING_EQUIPMENT_STATISTICS_SUMMARY
})

const headTitle = computed(() => {
  if (isSummaryCompanyElectricity.value) {
    if (tabId.value === REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_1)
      return `${dayjs(props.month).format('YYYY年MM月')} - ${props.title ?? '电量电费汇总表'}`
    else if (tabId.value === REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_2)
      return `${dayjs(props.month).format('YYYY年MM月')} - ${props.title ?? '生产单位电量电费成本表'}`
    else
      return `${dayjs(props.month).format('YYYY年MM月')} - ${props.title ?? '转供、外委单位用电明细表'}`
  }
  if (isSummaryCompanyWeight.value)
    return `${dayjs(props.month).format('YYYY年MM月')} - ${props.title ?? '水平衡汇总报表'}`
  if (isSummaryCompanyElectricityCategory.value)
    return `${dayjs(props.month).format('YYYY年MM月')} - ${props.title ?? '分类用电情况汇总报表'}`
  if (isSummaryCompanyPrimaryElectricityDevice.value)
    return `${dayjs(props.month).format('YYYY年MM月')} - ${props.title ?? '主要耗能设备统计汇总表'}`
  return ''
})

const tabsIdMap1 = {
  /** 汇总表 */
  [REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_1]: SummaryCompanyElectricityReport1,
  /** 成本表 */
  [REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_2]: SummaryCompanyElectricityReport2,
  /** 转供电 */
  [REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_3]: SummaryCompanyElectricityReport3,
}

const tabsIdMap2 = {
  /** 主通风机 */
  [REPORT_FORM_ID.SUMMARY_MAIN_VENTILATOR]: SummaryCompanyPrimaryElectricityDeviceReport1,
  /** 主排水 */
  [REPORT_FORM_ID.SUMMARY_MAIN_DRAINAGE]: SummaryCompanyPrimaryElectricityDeviceReport2,
  /** 空压机 */
  [REPORT_FORM_ID.SUMMARY_AIR_COMPRESSOR]: SummaryCompanyPrimaryElectricityDeviceReport3,
  /** 主井皮带 */
  [REPORT_FORM_ID.SUMMARY_MAIN_SHAFT_BELT]: SummaryCompanyPrimaryElectricityDeviceReport4,
  /** 综采生产 */
  [REPORT_FORM_ID.SUMMARY_COMBINED_MINING_PRODUCTION]: SummaryCompanyPrimaryElectricityDeviceReport5,
  /** 掘进生产 */
  [REPORT_FORM_ID.SUMMARY_TUNNELING_PRODUCTION]: SummaryCompanyPrimaryElectricityDeviceReport6,
}

const tabsIdMap = computed(() => {
  if (isSummaryCompanyElectricity.value)
    return tabsIdMap1
  if (isSummaryCompanyPrimaryElectricityDevice.value)
    return tabsIdMap2
  return {} as any
})
const tabId = ref<any>()
const tabs1 = [
  { name: '汇总表', id: REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_1 },
  { name: '成本表', id: REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_2 },
  { name: '转供电', id: REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_3 },
]
const tabs2 = [
  { name: '主通风机', id: REPORT_FORM_ID.SUMMARY_MAIN_VENTILATOR },
  { name: '主排水', id: REPORT_FORM_ID.SUMMARY_MAIN_DRAINAGE },
  { name: '空压机', id: REPORT_FORM_ID.SUMMARY_AIR_COMPRESSOR },
  { name: '主井皮带', id: REPORT_FORM_ID.SUMMARY_MAIN_SHAFT_BELT },
  { name: '综采生产', id: REPORT_FORM_ID.SUMMARY_COMBINED_MINING_PRODUCTION },
  { name: '掘进生产', id: REPORT_FORM_ID.SUMMARY_TUNNELING_PRODUCTION },
]
const tabs = computed(() => {
  if (isSummaryCompanyElectricity.value)
    return tabs1
  if (isSummaryCompanyPrimaryElectricityDevice.value)
    return tabs2
  return []
})

function handleTabChange(name: TabPaneName) {
  const target = tabs.value.find(v => v.id === name)
  if (target) {
    tabId.value = target.id
  }
  emit('tabChange', name)
}

function saveForTab(): Promise<boolean> {
  return new Promise<boolean>((resolve, reject) => {
    if (!isSummaryCompanyElectricity.value)
      return resolve(true);
    (reportRef.value as any)?.submitForTab().then(() => {
      resolve(true)
    }).catch(() => {
      reject(false)
    })
  })
}

function tabBeforeLeave(activeName: TabPaneName, oldActiveName: TabPaneName) {
  console.log(`activeName: ${activeName}, oldActiveName: ${oldActiveName}`)
  return new Promise<boolean>((resolve, reject) => {
    const hasChanged = (reportRef.value as any)?.checkHash?.()
    if (hasChanged) {
      ElMessageBox.confirm('当前页面有未保存的内容，是否保存？', '提示', {
        confirmButtonText: '保存',
        cancelButtonText: '丢弃',
        distinguishCancelAndClose: true,
        type: 'warning',
      }).then(() => { // confirm
        props.whenTabBeforeLeave(saveForTab).then(() => {
          resolve(true)
        }).catch(() => {
          reject(false)
        })
      }).catch((res) => { // close / cancel
        if (res === 'close') {
          reject(false)
        }
        else if (res === 'cancel') {
          resolve(true)
        }
      })
    }
    else {
      resolve(true)
    }
  })
}

onMounted(() => {
  if (isSummaryCompanyElectricity.value) {
    // 强制显示成本表
    tabId.value = props.forceShowTab ? tabs1[1].id : tabs1[0].id
    if (props.forceShowTab) {
      emit('tabChange', tabs1[1].id)
    }
  }
  else if (isSummaryCompanyPrimaryElectricityDevice.value) {
    tabId.value = tabs2[0].id
  }
})

defineExpose({
  getDataFromSummaryCompanyElectricity() {
    if (isSummaryCompanyElectricity.value && reportRef.value) {
      (reportRef.value as any).validate()
        .then(() => {
          const data = (reportRef.value as any).getData?.()
          if (data) {
            // console.log(data)
            saveReportDataOfSummaryCompanyElectricityCost(data)
              .then(() => {
                ElMessage.success('保存成功');
                // 保存成功后更新hash
                (reportRef.value as any).generateHash()
              })
          }
        }).catch(() => {})
    }
    return {}
  },
})
</script>

<template>
  <div class="flex flex-1 flex-col p-4">
    <div class="relative flex flex-shrink-0 justify-center">
      <span class="fs-24 mr-2 block">{{ headTitle }}</span>
      <slot name="action" />
    </div>
    <div v-if="isSummaryCompanyWeight" class="flex items-center justify-end">
      <span class="fs-14 text-gray">单位：吨</span>
    </div>
    <div class="flex-1 overflow-hidden" :class="{ 'mt-3': isSummaryCompanyWeight, 'mt-5': !isSummaryCompanyWeight }">
      <SummaryCompanyWeightReport v-if="isSummaryCompanyWeight" ref="reportRef" :time="month" />
      <SummaryCompanyElectricityCategoryReport v-else-if="isSummaryCompanyElectricityCategory" ref="reportRef" :time="month" />
      <div v-else-if="isSummaryCompanyPrimaryElectricityDevice || isSummaryCompanyElectricity" class="h-full w-full flex">
        <div class="w-30 flex-shrink-0">
          <div class="h-full w-full flex flex-col items-end gap-4 px-3">
            <ElTabs v-model="tabId" tab-position="left" :before-leave="tabBeforeLeave" @tab-change="handleTabChange">
              <ElTabPane v-for="item in tabs" :key="item.id" :label="item.name" :name="item.id" />
            </ElTabs>
          </div>
        </div>
        <div class="flex-1 overflow-auto">
          <component :is="tabsIdMap[tabId]" ref="reportRef" :time="month" :readonly="readonly" />
        </div>
      </div>
    </div>
  </div>
</template>
